package com.platform.comm.feign;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.platform.comm.exceptions.RestApiException;
import feign.Response;
import feign.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.util.Map;


/**
 * feign错误状态解码器
 *
 * @author wxw Created on 2021/11/30
 */
@Slf4j
@Configuration
public class FeignClientErrorDecoder implements feign.codec.ErrorDecoder {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public Exception decode(String s, Response response) {
        if (response.status() != HttpStatus.OK.value()) {
            if (response.status() == HttpStatus.SERVICE_UNAVAILABLE.value()) {
                String errorContent;
                try {
                    errorContent = Util.toString(response.body().asReader());
                    Map<String, String> map = MAPPER.readValue(errorContent, new TypeReference<Map<String, String>>() {
                    });
                    return new RestApiException(map.getOrDefault("message","未知错误"));
                } catch (IOException e) {
                    e.printStackTrace();
                    return new RestApiException("未知错误");
                }
            }
        }
        return new RestApiException("未知错误");
    }
}
